package demo2;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-08-16
 * Time: 22:44
 */
public class Test {
    //反射TestEnum

    public static void func(){ //另一种写法：public static void func() throws ClassNotFoundException.....
        try{
            Class<?> c1 = Class.forName("demo2.TestEnum");//生成Class对象
            /*
            * 在反射时，需要给反射对象的父类，的构造方法也进行传参初始化
            * 相应的实例化对象时的传参也要匹配上
            * 重点：不能通过反射来创建一个枚举对象*/
            Constructor<?> constructor =
                    c1.getDeclaredConstructor(String.class , int.class , int.class , String.class);//带两个参数的构造方法,注意参数的写法
            constructor.setAccessible(true);//让编译器放行

            TestEnum testEnum = (TestEnum) constructor.newInstance("白色",9 , 6,"棕色");//实例化对象顺便传参，
            System.out.println(testEnum);//打印toString方法



        }catch(ClassNotFoundException e){
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        func();//在反射时，需要给反射对象的父类，的构造方法也进行传参初始化
    }

}
